package com.aopcinemas.cinema.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hsqldb.types.Types;

import com.aopcinemas.cinema.model.Client;
import com.aopcinemas.cinema.model.Invoice;
import com.aopcinemas.cinema.model.Session;

public class InvoiceDao {

    private Connection connection;

    public InvoiceDao(Connection connection) {
        this.connection = connection;
    }

    public List<Invoice> getInvoices(long clientId) {
        Client client = new Client();
        client.setId(clientId);
        return getInvoices(client);
    }

    public List<Invoice> getInvoices(Client client) {

        List<Invoice> invoices = new ArrayList<Invoice>();

        try {
            PreparedStatement st = connection.prepareStatement("select * from invoice where client_id = ?");
            st.setLong(1, client.getId());
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                Invoice invoice = new Invoice();
                invoice.setClient(client);
                invoice.setPrice(rs.getDouble("price"));
                invoices.add(invoice);
            }

            rs.close();
            st.close();
        } catch (SQLException e) {
            throw new RuntimeException("System error", e);
        }

        return invoices;
    }

    public void addInvoice(Invoice invoice) {
        try {

            CallableStatement ct = connection.prepareCall("call new_invoice(?,?,?)");
            ct.registerOutParameter(1, Types.BIGINT);
            ct.setLong(2, invoice.getClient().getId());
            ct.setDouble(3, invoice.getPrice());
            ct.execute();

            invoice.setId(ct.getLong(1));

            PreparedStatement st = connection.prepareStatement("update session set invoice_id = ? where id = ?");
            st.setLong(1, invoice.getId());
            for (Session session : invoice.getSessions()) {
                st.setLong(2, session.getId());
                int rows = st.executeUpdate();
                if (rows <= 0) {
                    throw new RuntimeException("Can't update session");
                }
            }

            st.close();
        } catch (SQLException e) {
            throw new RuntimeException("System error", e);
        }

    }
}
